<?php


namespace app\common\util;

class ApiUtil
{

    /**
     * 响应码
     */
    const CODE_SUCCESS = 200;
    const CODE_FAIL = -1;
    const CODE_NOT_AUTH = 401; //未登录
    const CODE_SERVER_ERROR = 500; // 异常错误

    /**
     * class common function
     * @param $result
     * @param $msg
     * @param $code
     * @return \think\response\Json
     */
    private static function buildResponse($result, $msg, $code, $logCode = null){
        $return = [
            "data" => $result,
//            "msg" => CommonUtil::lang($msg),
            "msg" => $msg,
            "code" => $code
        ];
        if ($logCode != null){
            $return['log'] = $logCode;
        }
        return json($return, 200);
    }

    /**
     * normal response
     * @param array $result
     * @param string $msg
     * @param int $code
     * @return \think\response\Json
     */
    public static function normal($result = [], $msg = "请求成功", $code = self::CODE_SUCCESS){
        return self::buildResponse($result, $msg, $code);
    }

    /**
     * @param $logCode
     * @param array $result
     * @param string $msg
     * @param int $code
     * @return \think\response\Json
     */
    public static function error($logCode, $result = [], $msg = "请求失败", $code = self::CODE_FAIL){
        return self::buildResponse($result, $msg, $code, $logCode);
    }


    /**
     * 触发异常
     * @param int $status
     * @param string $msg
     */
    public static function abort(string $msg = '', int $code = self::CODE_SERVER_ERROR){
        abort($code, $msg);
    }


    /**
     * 异常
     * @param Exception $exception
     * @return \think\response\Json
     */
    public static function excep(\Exception $exception){
        $data = [
            'msg'=>$exception->getMessage(),
            'code'=>self::CODE_SERVER_ERROR,
//            'log_code'=>self::logInfo($exception)
        ];
        return json($data);
    }
}